package com.bazhua.bazo.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bazhua.bazo.repository.entity.Area;
import com.bazhua.bazo.repository.entity.ShopInfo;
import com.bazhua.bazo.repository.entity.WechatUser;
import com.bazhua.bazo.repository.mapper.ShopInfoMapper;
import com.bazhua.bazo.repository.model.*;
import com.bazhua.bazo.repository.model.result.CommonResult;
import com.bazhua.bazo.repository.model.result.PageListResult;
import com.bazhua.bazo.repository.model.result.ResultUtils;
import com.bazhua.bazo.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Service
public class ShopInfoServiceImpl extends ServiceImpl<ShopInfoMapper, ShopInfo> implements IShopInfoService {

    @Autowired
    private IWechatUserService wechatUserService;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private IAgentUserService agentUserService;

    public List<Long> getShopIds(Long areaId, Long street) {
        QueryWrapper<ShopInfo> shopInfoQueryWrapper = new QueryWrapper<>();
        shopInfoQueryWrapper.eq("shop_status", 2);
        if (areaId != null && areaId > 0L)
            shopInfoQueryWrapper.eq("shop_area_id", areaId);
        if (street != null && street > 0L)
            shopInfoQueryWrapper.eq("shop_street_id", street);
        List<ShopInfo> shopInfos = baseMapper.selectList(shopInfoQueryWrapper);
        return shopInfos.stream().map(x -> x.getId()).collect(Collectors.toList());
    }

    @Override
    public CommonResult registerShop(SaveShopModel model) {

        if (StringUtils.isBlank(model.getShopAdminOpenid()))
            return ResultUtils.error(90200, "openID不能为空");
        if (model.getShopAdmin() <= 0)
            return ResultUtils.error(90200, "用户ID不能为空");

        boolean isnew = false;
        QueryWrapper<ShopInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_admin_openid", model.getShopAdminOpenid());
        ShopInfo info = baseMapper.selectOne(wrapper);

        if (info != null && info.getShopStatus().equals(2))
            return ResultUtils.error(90090, "已存在商户");


        if (StringUtils.isBlank(model.getShopName()))
            return ResultUtils.error(90200, "商户名称不能为空");
        if (StringUtils.isBlank(model.getIdcardNegative()))
            return ResultUtils.error(90200, "身份证照片不能为空");
        if (StringUtils.isBlank(model.getIdcardPositive()))
            return ResultUtils.error(90200, "身份证照片不能为空");
        if (StringUtils.isBlank(model.getShopAdminLogo()))
            return ResultUtils.error(90200, "商户主微信二维码不能为空");
        if (StringUtils.isBlank(model.getShopIndustry()))
            return ResultUtils.error(90200, "商户行业不能为空");
        if (StringUtils.isBlank(model.getShopLicense()))
            return ResultUtils.error(90200, "营业执照不能为空");
        if (StringUtils.isBlank(model.getShopAdminName()))
            return ResultUtils.error(90200, "商户联系人不能为空");
        if (StringUtils.isBlank(model.getShopPhone()))
            return ResultUtils.error(90200, "商户联系电话不能为空");
        if (StringUtils.isBlank(model.getShopLogo()))
            return ResultUtils.error(90200, "商户logo不能为空");
        if (model.getShopAreaId() == null && model.getShopAreaId() <= 0)
            return ResultUtils.error(90200, "商户区域不能为空");
        if (model.getLatitude() == null || model.getLongitude() == null)
            return ResultUtils.error(90200, "商户经纬度不能为空");
        if (StringUtils.isBlank(model.getShopAddressName()))
            return ResultUtils.error(90200, "商户地址名称不能为空");


        if (info == null) {
            info = new ShopInfo();
            info.setCreateTime(new Date());
            isnew = true;
        }

        info.setIdcardNegative(model.getIdcardNegative());
        info.setIdcardPositive(model.getIdcardPositive());
        info.setShopAdmin(model.getShopAdmin());
        info.setShopAdminOpenid(model.getShopAdminOpenid());
        info.setShopAdminLogo(model.getShopAdminLogo());
        info.setShopIndustry(model.getShopIndustry());
        info.setShopLicense(model.getShopLicense());
        info.setShopName(model.getShopName());
        info.setShopPhone(model.getShopPhone());
        info.setShopRemark(model.getShopRemark());
        info.setLatitude(model.getLatitude());
        info.setShopAddress(model.getShopAddress());
        info.setLongitude(model.getLongitude());
        info.setShopStatus(ShopStatus.UnderReview);
        info.setShopLogo(model.getShopLogo());
        info.setShopAreaId(model.getShopAreaId());
        info.setShopStreetId(model.getShopStreetId());
        info.setShopAdminName(model.getShopAdminName());
        info.setShopAddressName(model.getShopAddressName());
        info.setShopExtensionUser(model.getShopExtensionUser());

        if (isnew) {
            baseMapper.insert(info);
        } else
            baseMapper.updateById(info);

        return ResultUtils.ok();

    }

    @Override
    public CommonResult updateShop(UpdateShopInfoModel model) {
        ShopInfo info = baseMapper.selectById(model.getId());
        if (info == null)
            return ResultUtils.error(90801, "数据不存在");


        if (StringUtils.isBlank(model.getShopName()))
            return ResultUtils.error(90200, "商户名称不能为空");
        if (StringUtils.isBlank(model.getShopAdminLogo()))
            return ResultUtils.error(90200, "商户主微信二维码不能为空");
        if (StringUtils.isBlank(model.getShopAdminName()))
            return ResultUtils.error(90200, "商户联系人不能为空");
        if (StringUtils.isBlank(model.getShopPhone()))
            return ResultUtils.error(90200, "商户联系电话不能为空");
        if (StringUtils.isBlank(model.getShopLogo()))
            return ResultUtils.error(90200, "商户logo不能为空");
        if (model.getShopAreaId() == null && model.getShopAreaId() <= 0)
            return ResultUtils.error(90200, "商户区域不能为空");
        if (model.getShopStreetId() == null && model.getShopStreetId() <= 0)
            return ResultUtils.error(90200, "商户社区不能为空");
        if (model.getLatitude() == null || model.getLongitude() == null)
            return ResultUtils.error(90200, "商户经纬度不能为空");
        if (StringUtils.isBlank(model.getShopAddressName()))
            return ResultUtils.error(90200, "商户地址名称不能为空");
        if (StringUtils.isBlank(model.getShopAddress()))
            return ResultUtils.error(90200, "商户地址不能为空");

        info.setShopExtensionUser(model.getShopExtensionUser());
        info.setShopAdminLogo(model.getShopAdminLogo());
        info.setShopName(model.getShopName());
        info.setShopPhone(model.getShopPhone());
        info.setShopRemark(model.getShopRemark());
        info.setLatitude(model.getLatitude());
        info.setLongitude(model.getLongitude());
        info.setShopLogo(model.getShopLogo());
        info.setShopAreaId(model.getShopAreaId());
        info.setShopAdminName(model.getShopAdminName());
        info.setShopStreetId(model.getShopStreetId());
        info.setShopAddressName(model.getShopAddressName());
        info.setShopAddress(model.getShopAddress());
        baseMapper.updateById(info);
        return ResultUtils.ok();
    }

    @Override
    public CommonResult UpdateShopStatus(Long shopId, Integer status) {
        ShopInfo shop = baseMapper.selectById(shopId);
        if (shop == null) return ResultUtils.error(90010, "查询数据为空");
        if (!shop.getShopStatus().equals(status) && status.equals(ShopStatus.Approved))
            shop.setShopStatus(ShopStatus.Approved);

        if (!shop.getShopStatus().equals(status) && status.equals(ShopStatus.UnApproved))
            shop.setShopStatus(ShopStatus.UnApproved);

        if (!shop.getShopStatus().equals(status) && status.equals(ShopStatus.Forbid))
            shop.setShopStatus(ShopStatus.Forbid);

        baseMapper.updateById(shop);

        if (status.equals(ShopStatus.Approved)) {
            Long userId = shop.getShopAdmin();
            WechatUser user = wechatUserService.getById(userId);
            user.setUserType(UserType.ShopAdmin);
            wechatUserService.updateById(user);
        }
        return ResultUtils.ok();
    }

    @Override
    public PageListResult SearchShop(SearchShopModel model) {

        QueryWrapper<ShopInfo> wrapper = new QueryWrapper<>();
        if (model.getShopAdmin() != null && model.getShopAdmin() > 0)
            wrapper.eq("shop_admin", model.getShopAdmin());
        if (!StringUtils.isBlank(model.getShopIndustry()))
            wrapper.like("shop_industry", model.getShopIndustry());
        if (model.getShopAreaId() != null && model.getShopAreaId() > 0L)
            wrapper.eq("shop_area_id", model.getShopAreaId());
        if (model.getShopStreetId() != null && model.getShopStreetId() > 0L)
            wrapper.eq("shop_street_id", model.getShopAreaId());
        if (!StringUtils.isBlank(model.getShopName()))
            wrapper.eq("shop_name", model.getShopName());
        if (!StringUtils.isBlank(model.getShopPhone()))
            wrapper.eq("shop_phone", model.getShopPhone());
        if (model.getShopStatus() != null && model.getShopStatus() > 0)
            wrapper.eq("shop_status", model.getShopStatus());
        if (model.getShopExtensionUser() != null && model.getShopExtensionUser() > 0)
            wrapper.eq("shop_extension_user", model.getShopExtensionUser());

        Page<ShopInfo> page = new Page<>(model.getPageNum(), model.getPageSize());
        return getPage(wrapper, page);
    }

    public PageListResult SearchShopByAgentId(SearchShopModel model, Long agentId) {
        QueryWrapper<ShopInfo> wrapper = new QueryWrapper<>();
        List<Long> userIds = agentUserService.getUserIdsByAgentId(agentId);
        wrapper.in("shop_extension_user", userIds);
        Page<ShopInfo> page = new Page<>(model.getPageNum(), model.getPageSize());
        return getPage(wrapper, page);
    }

    private PageListResult getPage(QueryWrapper<ShopInfo> wrapper, Page<ShopInfo> page) {
        page = baseMapper.selectPage(page, wrapper);
        if (page.getTotal() > 0) {
            Page<ShopInfoDetailModel> detailPage = new Page<>();
            detailPage.setPages(page.getPages());
            detailPage.setCurrent(page.getCurrent());
            detailPage.setSize(page.getSize());
            detailPage.setTotal(page.getTotal());
            List<ShopInfoDetailModel> list = new ArrayList<>();
            for (ShopInfo shop : page.getRecords()) {
                ShopInfoDetailModel detailModel = new ShopInfoDetailModel();
                detailModel.setId(shop.getId());
                detailModel.setCreateTime(shop.getCreateTime());
                detailModel.setIdcardNegative(shop.getIdcardNegative());
                detailModel.setIdcardPositive(shop.getIdcardPositive());
                detailModel.setLatitude(shop.getLatitude());
                detailModel.setLongitude(shop.getLongitude());
                detailModel.setShopAddress(shop.getShopAddress());
                detailModel.setShopAddressName(shop.getShopAddressName());
                detailModel.setShopAdmin(shop.getShopAdmin());
                if (shop.getShopAreaId() != null && shop.getShopAreaId() > 0) {
                    Area area = areaService.getById(shop.getShopAreaId());
                    detailModel.setShopAreaId(area.getId());
                    detailModel.setShopArea(area.getAreaName());
                }
                if (shop.getShopStreetId() != null && shop.getShopStreetId() > 0) {
                    Area street = areaService.getById(shop.getShopStreetId());
                    detailModel.setShopStreetId(street.getId());
                    detailModel.setShopStreet(street.getAreaName());
                }
                detailModel.setShopAdminLogo(shop.getShopAdminLogo());
                detailModel.setShopAdminName(shop.getShopAdminName());
                detailModel.setShopAdminOpenid(shop.getShopAdminOpenid());
                detailModel.setShopAddress(shop.getShopAddress());
                detailModel.setShopIndustry(shop.getShopIndustry());
                detailModel.setShopLogo(shop.getShopLogo());
                detailModel.setShopLicense(shop.getShopLicense());
                detailModel.setShopName(shop.getShopName());
                detailModel.setShopPhone(shop.getShopPhone());
                detailModel.setShopRemark(shop.getShopRemark());
                detailModel.setShopStatus(shop.getShopStatus());
                if (shop.getShopExtensionUser() != null && shop.getShopExtensionUser() > 0) {
                    WechatUser user = wechatUserService.getById(shop.getShopExtensionUser());
                    if(user!=null){
                        detailModel.setShopExtensionName(user.getUserName());
                        detailModel.setShopExtensionPhone(user.getPhone());
                        detailModel.setShopExtensionUser(user.getId());
                    }
                }

                list.add(detailModel);
            }
            detailPage.setRecords(list);
            return ResultUtils.pageOk(detailPage);
        } else
            return ResultUtils.pageError(90100, "查询数据为空");
    }

    @Override
    public CommonResult GetShopByOpenId(String openId) {
        QueryWrapper<ShopInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_admin_openid", openId);
        ShopInfo shop = baseMapper.selectOne(wrapper);
        if (shop == null)
            return ResultUtils.error(90001, "查询数据为空");

        ShopInfoDetailModel detailModel = new ShopInfoDetailModel();
        detailModel.setId(shop.getId());
        detailModel.setCreateTime(shop.getCreateTime());
        detailModel.setIdcardNegative(shop.getIdcardNegative());
        detailModel.setIdcardPositive(shop.getIdcardPositive());
        detailModel.setLatitude(shop.getLatitude());
        detailModel.setLongitude(shop.getLongitude());
        detailModel.setShopAddress(shop.getShopAddress());
        detailModel.setShopAddressName(shop.getShopAddressName());
        detailModel.setShopAdmin(shop.getShopAdmin());
        detailModel.setShopAdminLogo(shop.getShopAdminLogo());
        detailModel.setShopAdminName(shop.getShopAdminName());
        detailModel.setShopAdminOpenid(shop.getShopAdminOpenid());
        detailModel.setShopAddress(shop.getShopAddress());
        detailModel.setShopIndustry(shop.getShopIndustry());
        detailModel.setShopLogo(shop.getShopLogo());
        detailModel.setShopLicense(shop.getShopLicense());
        detailModel.setShopName(shop.getShopName());
        detailModel.setShopPhone(shop.getShopPhone());
        detailModel.setShopRemark(shop.getShopRemark());
        detailModel.setShopStatus(shop.getShopStatus());
        if (shop.getShopAreaId() != null && shop.getShopAreaId() > 0) {
            Area area = areaService.getById(shop.getShopAreaId());
            detailModel.setShopAreaId(area.getId());
            detailModel.setShopArea(area.getAreaName());
        }
        if (shop.getShopStreetId() != null && shop.getShopStreetId() > 0) {
            Area street = areaService.getById(shop.getShopStreetId());
            detailModel.setShopStreetId(street.getId());
            detailModel.setShopStreet(street.getAreaName());
        }
        if (shop.getShopExtensionUser() != null && shop.getShopExtensionUser() > 0) {
            WechatUser user = wechatUserService.getById(shop.getShopExtensionUser());
            detailModel.setShopExtensionName(user.getUserName());
            detailModel.setShopExtensionPhone(user.getPhone());
            detailModel.setShopExtensionUser(user.getId());
        }

        return ResultUtils.ok(detailModel);
    }

    @Override
    public CommonResult GetShopById(Long Id) {
        ShopInfo shop = baseMapper.selectById(Id);
        if (shop == null)
            return ResultUtils.error(90001, "查询数据为空");

        ShopInfoDetailModel detailModel = new ShopInfoDetailModel();
        detailModel.setId(shop.getId());
        detailModel.setCreateTime(shop.getCreateTime());
        detailModel.setIdcardNegative(shop.getIdcardNegative());
        detailModel.setIdcardPositive(shop.getIdcardPositive());
        detailModel.setLatitude(shop.getLatitude());
        detailModel.setLongitude(shop.getLongitude());
        detailModel.setShopAddress(shop.getShopAddress());
        detailModel.setShopAddressName(shop.getShopAddressName());
        detailModel.setShopAdmin(shop.getShopAdmin());
        detailModel.setShopAdminLogo(shop.getShopAdminLogo());
        detailModel.setShopAdminName(shop.getShopAdminName());
        detailModel.setShopAdminOpenid(shop.getShopAdminOpenid());
        detailModel.setShopAddress(shop.getShopAddress());
        detailModel.setShopIndustry(shop.getShopIndustry());
        detailModel.setShopLogo(shop.getShopLogo());
        detailModel.setShopLicense(shop.getShopLicense());
        detailModel.setShopName(shop.getShopName());
        detailModel.setShopPhone(shop.getShopPhone());
        detailModel.setShopRemark(shop.getShopRemark());
        detailModel.setShopStatus(shop.getShopStatus());
        if (shop.getShopAreaId() != null && shop.getShopAreaId() > 0) {
            Area area = areaService.getById(shop.getShopAreaId());
            detailModel.setShopAreaId(area.getId());
            detailModel.setShopArea(area.getAreaName());
        }
        if (shop.getShopStreetId() != null && shop.getShopStreetId() > 0) {
            Area street = areaService.getById(shop.getShopStreetId());
            detailModel.setShopStreetId(street.getId());
            detailModel.setShopStreet(street.getAreaName());
        }
        if (shop.getShopExtensionUser() != null && shop.getShopExtensionUser() > 0) {
            WechatUser user = wechatUserService.getById(shop.getShopExtensionUser());
            detailModel.setShopExtensionName(user.getUserName());
            detailModel.setShopExtensionPhone(user.getPhone());
            detailModel.setShopExtensionUser(user.getId());
        }

        return ResultUtils.ok(detailModel);
    }

    @Override
    public CommonResult CheckShopByOpenId(String openId) {
        QueryWrapper<ShopInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_admin_openid", openId);
        ShopInfo info = baseMapper.selectOne(wrapper);
        Integer behavior = 0;
        if (info == null || info.getId() <= 0 || info.getShopStatus().equals(1) || info.getShopStatus().equals(4))
            behavior = 1;
        if (info.getShopStatus().equals(2))
            behavior = 2;
        if (info.getShopStatus().equals(3))
            behavior = 3;

        return ResultUtils.ok(behavior);
    }

}
